package com.qf.first.controller;


import com.qf.first.entity.User;
import com.qf.first.exceptions.BaseException;
import com.qf.first.pojo.bo.Code;
import com.qf.first.pojo.vo.RespVo;
import com.qf.first.pojo.vo.UserRole;
import com.qf.first.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "用户模块")
@RestController
@RequestMapping(value = "/user")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;

    /**
     * 根据用户字段查询用户
     * @param user  用户实体类
     * @return
     */
    @ApiOperation("根据User字段添加用户")
    @PostMapping("/addUser")
    public RespVo addUser(@RequestBody User user){
        int i = userService.insertUser(user);
        if (i==1){
            return convertSuccess("注册成功");
        }else {
            return convertFail("注册失败");
        }

    }

    /**
     * 根据用户字段检查用户是否粗在
     * @param user 用户实体类
     * @return
     */
    @ApiOperation("检查用户是否存在功能")
    @GetMapping("/checkUser")
    public RespVo checkUser(User user){
        if (user==null){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"用户不能为空");
        }
        User user1 = userService.checkUser(user);
        if (user1==null){
            return convertSuccess("用户名可用");
        }
        return convertFail("用户名已存在");
    }

    /**
     * 登录功能
     * @param user 用户实体类
     * @param code 验证码
     * @param session 会话区  存储登录的用户id
     * @return
     */
    @ApiOperation("登录功能")
    @RequestMapping("/login")
    public RespVo login(User user,Code code, HttpSession session){
        Boolean flag = userService.checkCode(code.getCode(), session);
        if (!flag){
            return convertFail("验证码错误");
        }
        User user1 = userService.checkUser(user);
        if (user1==null){
            return convertFail("用户名或密码错误");
        }
        session.setAttribute("id",user1.getUserId());
        return convertSuccess(user1);
    }

    /**
     * 根据会话区的id获取用户信息
     * @param session 会话区
     * @return
     */
    @ApiOperation("获取用户功能")
    @GetMapping("/getUser")
    public RespVo getUser(HttpSession session){
        Long id = (Long) session.getAttribute("id");
        if (id==null){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"用户未登录");
        }
        User user = new User();
        user.setUserId(id);
        UserRole userRole = userService.getUser(user);
        System.out.println(userRole);
        return convertSuccess(userRole);
    }

    /**
     * 根据用户id检查用户密码是否正确
     * @param user  用户实体类
     * @param session 会话区
     * @return
     */
    @ApiOperation("检查密码是否正确")
    @GetMapping("/checkPassword")
    public RespVo checkPassword(User user,HttpSession session){
        Long id = (Long) session.getAttribute("id");
        if (id==null){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"用户未登录");
        }
        user.setUserId(id);
        if (user.getPassword()==null||user.getPassword()==""){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"密码不能为空");
        }
        User user1 = userService.checkUser(user);
        if (user1==null){
            return convertFail("原密码错误");
        }
        return convertSuccess("原密码正确");
    }

    /**
     * 根据用户字段修改用户
     * @param user 用户实体类
     * @param session 会话区
     * @return
     */
    @ApiOperation("修改用户")
    @GetMapping("/changePassword")
    public RespVo changePassword(User user,HttpSession session){
        System.out.println(user);
        if (user==null){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"你输入的数据为空");
        }
        Long id = (Long) session.getAttribute("id");
        if (id==null){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"用户未登录");
        }
        user.setUserId(id);
        int i = userService.updateUser(user);
        if (i==0){
            convertFail("修改失败");
        }

        return convertSuccess("修改成功");
    }

    /**
     * 忘记密码功能，根据用户明和电话查找用户
     * @param user 用户实体类
     * @return
     */
    @ApiOperation("根据用户名和电话检查用户是否存在")
    @GetMapping("/checkUserByPhone")
    public RespVo checkUserByPhone(User user){
        System.out.println(user);
        if (user==null){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"数据不能为空");
        }
        User user1 = userService.checkUser(user);
        if (user1==null){
            return convertFail("用户名或电话错误");
        }
        System.out.println(user1);
        return convertSuccess(user1);
    }

    /**
     * 修改用户密码
     * @param user 用户实体类
     * @return
     */
    @ApiOperation("修改密码")
    @GetMapping("/rePassword")
    public RespVo rePassword(User user){
        System.out.println(user);
        if (user==null){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"数据不能为空");
        }
        int i = userService.updateUser(user);
        if (i==0){
            return convertFail("密码修改失败");
        }
        return convertSuccess("密码修改成功");
    }

    /**
     * 上传图片功能
     * @param user 用户实体类 存储userId和图片名
     * @param file 前端传输过来的文件
     * @param session 会话区，用户获取登录的用户id
     * @param request 请求
     * @param response 响应
     * @return
     * @throws IOException
     */
    @ApiOperation("上传图片")
    @PostMapping(value = "/addImgUrl"
            ,consumes = "multipart/*",
            headers = "content-type=multipart/form-data"
    )
    public RespVo addImgUrl(User user, @ApiParam(value = "文件") MultipartFile file, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()){
            throw new BaseException(RespVo.CodeType.FAIL.getValue(),"上传文件为空");
        }
        String path = request.getSession().getServletContext().getRealPath("/images");
        //获取源文件的文件名
        String fileName = file.getOriginalFilename();
        fileName = UUID.randomUUID().toString()+"_"+fileName;
        // 检查图片存储路径是否存在，如果不存在，创建路径
        //创建目标文件，制定文件存储路径和文件名
        File uploadpath = new File(path,fileName);
        if (!uploadpath.exists()){
            uploadpath.mkdirs();
        }

        if (fileName!=null&&fileName.length()>0){
            try {
                file.transferTo(uploadpath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String imgUrl =fileName;
        System.out.println(path+ fileName);
        Long id = (Long) session.getAttribute("id");
        user.setUserId(id);
        user.setImgUrl(imgUrl);
        int i = userService.updateUser(user);
        if (i==0){
            return convertFail("保存失败");
        }
        return convertSuccess("user");
    }

    @ApiOperation("注销功能")
    @GetMapping("/logout")
    public RespVo logout(HttpSession session){
        session.removeAttribute("id");
        return convertSuccess("注销成功");
    }
}
